package com.imooc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.pojo.bo.ShopCartBO;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: foodie-dev
 * @description: 购物车接口控制器
 * @author: rZ
 * @create: 2020-02-21 17:06
 **/
@Api(value = "购物车接口的controller",tags = {"购物车接口相关的api"})
@RestController
@RequestMapping("/shopcart")
public class ShopCartController extends BaseController{

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 添加商品到购物车
     * @param userId
     * @param shopCartBO
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "添加商品到购物车",notes = "添加商品到购物车",httpMethod = "POST")
    @PostMapping("/add")
    public IMOOCJSONResult add(@RequestParam String userId,
                               @RequestBody ShopCartBO shopCartBO,
                               HttpServletRequest request,
                               HttpServletResponse response) throws JsonProcessingException {
        if (StringUtils.isBlank(userId)){
            return IMOOCJSONResult.errorMsg("");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String shaopCart = objectMapper.writeValueAsString(shopCartBO);
        System.out.println(shaopCart);
        //前端用户在登录的情况下，添加商品到购物车，会同时在后端同步购物车到redis缓存
        //需要判断当前购物车中包含已经存在的商品，如果存在则累加购买数量
        String shopCartJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        List<ShopCartBO> shopCartList = null;
        if (StringUtils.isNotBlank(shopCartJson)){
            //redis中已经有购物车了
            shopCartList = JsonUtils.jsonToList(shopCartJson,ShopCartBO.class);
            //判断购物车中是否存在已有商品，如果有的话counts累加
            boolean isHaving = false;
            for (ShopCartBO shopCart : shopCartList) {
                String specId = shopCart.getSpecId();
                if (specId.equals(shopCartBO.getSpecId())){
                    shopCart.setBuyCounts(shopCart.getBuyCounts()+shopCartBO.getBuyCounts());
                    isHaving = true;
                }
            }
            if (!isHaving){
                shopCartList.add(shopCartBO);
            }
        }else {
            //redis中没有购物车
            shopCartList = new ArrayList<>();
            //直接添加到购物车中
            shopCartList.add(shopCartBO);
        }
        //覆盖现有redis中的购物车
        redisOperator.set(FOODIE_SHOPCART+":"+userId,JsonUtils.objectToJson(shopCartList));
        return IMOOCJSONResult.ok();
    }


    @ApiOperation(value = "从购物车中删除商品",notes = "从购物车中删除商品",httpMethod = "POST")
    @PostMapping("/del")
    public IMOOCJSONResult del(@RequestParam String userId,
                               @RequestParam String itemSpecId,
                               HttpServletRequest request,
                               HttpServletResponse response) throws JsonProcessingException {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(itemSpecId)){
            return IMOOCJSONResult.errorMsg("参数不能为空");
        }
        //用户在页面删除购物车中的商品数据，如果此时用户已经登录，则需要同步删除redis购物车中的商品
        String shopCartJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        if (StringUtils.isNotBlank(shopCartJson)){
            //redis中已经有购物车
            List<ShopCartBO> shopCartList = JsonUtils.jsonToList(shopCartJson,ShopCartBO.class);
            //判断购物车中是否存在已有商品，如果有的话则删除
            for (ShopCartBO shopCartBO : shopCartList) {
                if (shopCartBO.getSpecId().equals(itemSpecId)){
                    shopCartList.remove(shopCartBO);
                    break;
                }
            }
            //覆盖现有redis中的购物车
            redisOperator.set(FOODIE_SHOPCART+":"+userId,JsonUtils.objectToJson(shopCartList));
        }
        return IMOOCJSONResult.ok();
    }
}
